package net.hyperz.water.levels;

import net.hyperz.water.levels.utils.StationContent;
import net.hyperz.water.levels.utils.StationContent.StationInformation;

import org.jsoup.nodes.Document;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class StationDetailFragment extends Fragment {
	
    public static final String ARG_ITEM_ID = "item_id";
    public static final String ARG_ITEM_NAME = "item_name";
    
    private View mRootView;
    private StationContent sc = new StationContent();
    
    String mItemId;
    String mItemName;
    
    public StationDetailFragment() {
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (getArguments().containsKey(ARG_ITEM_ID)) {
        	mItemId = getArguments().getString(ARG_ITEM_ID);
        }
        
        if (getArguments().containsKey(ARG_ITEM_NAME)) {
        	mItemName = getArguments().getString(ARG_ITEM_NAME);
        }
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	mRootView = inflater.inflate(R.layout.fragment_station_detail, container, false);
        if (mItemId != null) {
            
        	new LoadStationInformation().execute(mItemId);
        }
        return mRootView;
    }
    
    private class LoadStationInformation extends AsyncTask<String, Void, StationInformation> {
		ProgressDialog progress = new ProgressDialog(getActivity());
		
		@Override
        public void onPreExecute() {
			progress.setCanceledOnTouchOutside(false);
			progress.setCancelable(false);
			progress.setMessage("Loading Station Data ...");
			progress.show();
		}
		
		@Override
        public void onPostExecute(StationInformation si) {
			((TextView) mRootView.findViewById(R.id.station_name)).setText(si.ec_office);
			
			progress.dismiss();
		}
		
		@Override
		protected StationInformation doInBackground(String... params) {
			Document doc = new Document("http://www.wateroffice.ec.gc.ca");
			doc.html(StationContent.convertStreamToString(getActivity().getResources().openRawResource(R.raw.si)));
			return sc.getStationInformation(params[0], doc);
			//return sc.getStations(null);
		}
	}
}
